﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;
using System.IO;

namespace CSSoft.VNTower.Domain
{
    [Serializable]
    public class DailyReportFileItem : BaseItem
    {
        public string FileUrl { get; set; }
        public string FileType { get; set; }
        public string FileCode { get; set; }
        public string Project { get { return ProjectItem.Title; } }
        public ProjectItem ProjectItem { get; set; }
        public string Note { get; set; }
        public string PMAproved { get; set; }
        public bool PMAprovedCheckBox { get { return PMAproved == "Aproved"; } }
        public bool AllowDelete { get { return !PMAprovedCheckBox; } }
        public string PMComment { get; set; }
        public bool IsReporter { get; set; }
        public bool NotIsReporter { get { return !IsReporter; } }
        public bool IsProjectManager { get; set; }
        public bool NotIsProjectManager { get { return !IsProjectManager; } }
        
        public DailyReportFileItem() { ProjectItem = new ProjectItem(); }

        public DailyReportFileItem ReadItem(SPListItem item)
        {
            this.Item = item;
            FileType = CS2Convert.GetIconUrl(CS2Convert.ToString(item["DocIcon"]));
            FileCode = Path.GetFileNameWithoutExtension(CS2Convert.ToString(item["FileLeafRef"]));
            FileUrl = String.Format("{0}/{1}", CS2Web.CurrentWeb.Url, item.File.Url);
            ProjectItem = new ProjectItem { LookupValue = CS2Convert.ToLookupValue(item["Project"]) };
            Note = CS2Convert.ToString(item["Note"]);
            PMAproved = CS2Convert.ToString(item["PMAproved"]);
            PMComment = CS2Convert.ToString(item["PMComment"]);
            try {
                SPFieldUserValue reporter = CS2Convert.ToSPFieldUserValue(item["Author"]);
                IsReporter = reporter.User.ID == CS2Web.CurrentUser.ID;
            }
            catch { IsReporter = false; }
            try
            {
                SPList projectList = CS2Web.GetList(Constants.LIST_PROJECTS);
                SPQuery query = new SPQuery();
                query.Query = String.Format(@"<Where>
                      <And>
                         <Eq>
                            <FieldRef Name='ID' />
                            <Value Type='Counter'>{0}</Value>
                         </Eq>
                         <Eq>
                            <FieldRef Name='Manager' LookupId='TRUE' />
                            <Value Type='User'>{1}</Value>
                         </Eq>
                      </And>
                   </Where>", ProjectItem.Id, CS2Web.CurrentUser.ID);
                IsProjectManager = CS2SPQueryBuilder.HasItems(projectList.GetItems(query));
            }
            catch { IsProjectManager = false; }
            return this;
        }
    }
}
